package com.teichmann.core.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.log4j.Logger;

public class ConnectionUtils {

	static Logger logger = Logger.getLogger(ConnectionUtils.class.getSimpleName());

	public static HttpClient getClient() {
		HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);

		logger.debug("client is null. Instantiating... ");
		HttpClient client = new DefaultHttpClient(httpParams);

		return client;

	}

	/**
	 * @param url
	 * @return String Html content
	 * @throws Exception
	 */
	public static String get(HttpClient client, String url) throws IOException {

		logger.debug("request to " + url);

		HttpGet method = new HttpGet(URIUtils.encodePath(new StringBuffer(),
				url).toString());

		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		return client.execute(method, responseHandler);
	}

	public static String post(HttpClient client, String url, Map parameters)
			throws IOException {

		logger.debug("request to " + url);

		HttpParams httpParams = new BasicHttpParams();
		
		List<NameValuePair> param = new ArrayList<NameValuePair>();

		Iterator it = parameters.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> pairs = (Map.Entry<String, String>) it
					.next();
			httpParams.setParameter(pairs.getKey(), pairs.getValue());
			param.add(new BasicNameValuePair(pairs.getKey(), pairs.getValue()));
		}

		HttpPost method = new HttpPost(url);
		UrlEncodedFormEntity sendentity = new UrlEncodedFormEntity(param,
				HTTP.UTF_8);
		method.setEntity(sendentity);

		// Execute the method.
		ResponseHandler<String> responseHandler = new BasicResponseHandler();
		String response = client.execute(method, responseHandler);

		return response;
	}

}
